package com.vegetable.modules.service.baseData.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vegetable.common.utils.BankCardRedisService;
import com.vegetable.modules.entity.baseData.BankCard;
import com.vegetable.modules.entity.baseData.BankCardQueryDTO;
import com.vegetable.modules.mapper.baseData.BankCardMapper;
import com.vegetable.modules.service.baseData.IBankCardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 银行卡号 服务实现类
 * </p>
 *
 * @author vegetable
 * @since 2025-09-23
 */
@Slf4j
@Service
public class BankCardServiceImpl extends ServiceImpl<BankCardMapper, BankCard> implements IBankCardService {

    @Autowired
    private BankCardRedisService bankCardRedisService;
    
    @Autowired
    private BankCardMapper bankCardMapper;

    @Override
    public IPage<BankCard> queryPage(BankCardQueryDTO queryDTO) {
        QueryWrapper<BankCard> queryWrapper = new QueryWrapper<>();
        
        // 添加查询条件
        if (queryDTO.getAddressBookId() != null) {
            queryWrapper.eq("address_book_id", queryDTO.getAddressBookId());
        }
        
        if (queryDTO.getBankNo() != null && !queryDTO.getBankNo().isEmpty()) {
            queryWrapper.like("bank_no", queryDTO.getBankNo());
        }
        
        if (queryDTO.getStatus() != null) {
            queryWrapper.eq("status", queryDTO.getStatus());
        }
        
        queryWrapper.eq("is_del", 0);
        queryWrapper.orderByDesc("create_time");

        Page<BankCard> page = new Page<>(queryDTO.getPage(), queryDTO.getLimit());
        return this.page(page, queryWrapper);
    }

    @Override
    public List<BankCard> listByAddressBookId(Long addressBookId) {
        QueryWrapper<BankCard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("address_book_id", addressBookId);
        queryWrapper.eq("status", 1);
        queryWrapper.eq("is_del", 0);
        queryWrapper.orderByDesc("is_default");
        return this.list(queryWrapper);
    }

    @Override
    public List<BankCard> selectByBankNo(String bankNo) {
        QueryWrapper<BankCard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bank_no", bankNo);
        queryWrapper.eq("status", 1);
        queryWrapper.eq("is_del", 0);
        return this.list(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setDefault(Long id, Long addressBookId) {
        try {
            // 将该通讯录下的所有银行卡都设置为非默认
            QueryWrapper<BankCard> updateWrapper = new QueryWrapper<>();
            updateWrapper.eq("address_book_id", addressBookId);
            BankCard updateCard = new BankCard();
            updateCard.setIsDefault(0);
            this.update(updateCard, updateWrapper);
            
            // 将指定的银行卡设置为默认
            BankCard card = new BankCard();
            card.setId(id);
            card.setIsDefault(1);
            boolean result = updateById(card);
            
            // 更新Redis缓存
            if (result) {
                updateBankCardCache();
            }
            
            return result;
        } catch (Exception e) {
            log.error("设置默认银行卡失败，id: {}, addressBookId: {}", id, addressBookId, e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatch(Long addressBookId, List<String> bankNos) {
        try {
            // 删除原有的银行卡号
            QueryWrapper<BankCard> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("address_book_id", addressBookId);
            this.remove(deleteWrapper);
            
            // 批量插入新的银行卡号
            for (String bankNo : bankNos) {
                if (bankNo != null && !bankNo.trim().isEmpty()) {
                    BankCard card = new BankCard();
                    card.setAddressBookId(addressBookId);
                    card.setBankNo(bankNo.trim());
                    card.setStatus(1);
                    card.setIsDefault(0);
                    card.setIsDel(0);
                    bankCardMapper.insertIgnore(card);
                }
            }
            
            // 更新Redis缓存
            updateBankCardCache();
            return true;
        } catch (Exception e) {
            log.error("批量保存银行卡号失败，addressBookId: {}, bankNos: {}", addressBookId, bankNos, e);
            return false;
        }
    }

    
    public boolean updateById(BankCard entity) {
        boolean result = super.updateById(entity);
        if (result) {
            updateBankCardCache();
        }
        return result;
    }
    
    public boolean removeById(Long id) {
        boolean result = super.removeById(id);
        if (result) {
            updateBankCardCache();
        }
        return result;
    }
    
    /**
     * 更新银行卡缓存
     */
    private void updateBankCardCache() {
        try {
            QueryWrapper<BankCard> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1);
            queryWrapper.eq("is_del", 0);
            List<BankCard> bankCardList = this.list(queryWrapper);
            bankCardRedisService.cacheBankCardList(bankCardList);
        } catch (Exception e) {
            log.error("更新银行卡缓存失败", e);
        }
    }
}